import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { Info, Clock, Upload, FileAudio } from "lucide-react"
import toast from 'react-hot-toast'

import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from "@/components/ui/tooltip.tsx";
import {generateNote, uploadVideo, uploadAudio} from "@/services/note.ts";
import {useTaskStore} from "@/store/taskStore";
import { useState, useRef } from "react"
import NoteHistory from "@/pages/components/NoteHistory.tsx";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"

// ✅ 定义表单 schema
const formSchema = z.object({
    video_url: z.string().url("请输入正确的视频链接"),
    platform: z.string().nonempty("请选择平台"),
    quality: z.enum(["fast", "medium", "slow"], {
        required_error: "请选择音频质量",
    }),
    screenshot: z.boolean().optional(),
    link:z.boolean().optional(),
})


type NoteFormValues = z.infer<typeof formSchema>

const NoteForm = () => {
    const [selectedTaskId] = useState<string | null>(null)
    const [isUploading, setIsUploading] = useState(false)
    const [selectedFile, setSelectedFile] = useState<File | null>(null)
    const [selectedAudio, setSelectedAudio] = useState<File | null>(null)
    const fileInputRef = useRef<HTMLInputElement>(null)
    const audioInputRef = useRef<HTMLInputElement>(null)

    const tasks = useTaskStore((state) => state.tasks)
    const setCurrentTask=useTaskStore((state)=>state.setCurrentTask)
    const currentTaskId=useTaskStore(state=>state.currentTaskId )
    tasks.find((t) => t.id === selectedTaskId);
    const form = useForm<NoteFormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            video_url: "",
            platform: "bilibili",
            quality: "medium", // 默认中等质量
            screenshot: false,
        },
    })

    const isGenerating = false

    const onSubmit = async (data: NoteFormValues) => {
        console.log("🎯 提交内容：", data)
        await generateNote({
            video_url: data.video_url,
            platform: data.platform,
            quality: data.quality,
            screenshot:data.screenshot,
            link:data.link
        });
    }

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            setSelectedFile(e.target.files[0]);
        }
    }

    const handleFileUpload = async () => {
        if (!selectedFile) {
            toast.error("请先选择视频文件");
            return;
        }

        setIsUploading(true);
        try {
            const screenshot = form.getValues("screenshot") || false;
            
            await uploadVideo(selectedFile, screenshot);
            setSelectedFile(null);
            if (fileInputRef.current) {
                fileInputRef.current.value = "";
            }
        } catch (error) {
            console.error("文件上传失败", error);
        } finally {
            setIsUploading(false);
        }
    }

    const handleAudioChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            setSelectedAudio(e.target.files[0]);
        }
    }

    const handleAudioUpload = async () => {
        if (!selectedAudio) {
            toast.error("请先选择音频文件");
            return;
        }

        setIsUploading(true);
        try {
            await uploadAudio(selectedAudio, false);
            setSelectedAudio(null);
            if (audioInputRef.current) {
                audioInputRef.current.value = "";
            }
        } catch (error) {
            console.error("音频上传失败", error);
        } finally {
            setIsUploading(false);
        }
    }

    const triggerFileInput = () => {
        if (fileInputRef.current) {
            fileInputRef.current.click();
        }
    }

    const triggerAudioInput = () => {
        if (audioInputRef.current) {
            audioInputRef.current.click();
        }
    }

    return (
        <div className="flex flex-col h-full">
            <Tabs defaultValue="link" className="w-full">
                <TabsList className="grid grid-cols-3 mb-4">
                    <TabsTrigger value="link">视频链接</TabsTrigger>
                    <TabsTrigger value="upload">本地视频</TabsTrigger>
                    <TabsTrigger value="audio">音频上传</TabsTrigger>
                </TabsList>
                
                <TabsContent value="link">
                    <Form {...form}>
                        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                            <div className="space-y-2">
                                <div className="flex items-center justify-between my-3">
                                    <h2 className="block  ">视频链接</h2>
                                    <TooltipProvider>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <Info className="h-4 w-4 text-neutral-400 hover:text-primary cursor-pointer" />
                                            </TooltipTrigger>
                                            <TooltipContent>
                                                <p className="text-xs ">输入视频链接，支持哔哩哔哩、YouTube等平台</p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                </div>

                                <div className="flex gap-2">
                                    {/* 平台选择 */}
                                    <FormField
                                        control={form.control}
                                        name="platform"
                                        render={({ field }) => (
                                            <FormItem>
                                                <Select
                                                    onValueChange={field.onChange}
                                                    defaultValue={field.value}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger className="w-32">
                                                            <SelectValue placeholder="选择平台" />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="bilibili">哔哩哔哩</SelectItem>
                                                        <SelectItem value="youtube">Youtube</SelectItem>
                                                        {/*<SelectItem value="local">本地视频</SelectItem>*/}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    {/* 视频地址 */}
                                    <FormField
                                        control={form.control}
                                        name="video_url"
                                        render={({ field }) => (
                                            <FormItem className="flex-1">
                                                <FormControl>
                                                    <Input
                                                        placeholder="视频链接"
                                                        {...field}
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />
                                </div>
                                
                                <FormField
                                    control={form.control}
                                    name="quality"
                                    render={({ field }) => (
                                        <FormItem>
                                            <div className="flex items-center justify-between my-3">
                                                <h2 className="block  ">音频质量</h2>
                                                <TooltipProvider>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <Info className="h-4 w-4 text-neutral-400 hover:text-primary cursor-pointer" />
                                                        </TooltipTrigger>
                                                        <TooltipContent>
                                                            <p className="text-xs max-w-[200px]">质量越高，下载体积越大，速度越慢</p>
                                                        </TooltipContent>
                                                    </Tooltip>
                                                </TooltipProvider>
                                            </div>
                                            <Select
                                                onValueChange={field.onChange}
                                                defaultValue={field.value}
                                            >
                                                <FormControl>
                                                    <SelectTrigger className="w-full">
                                                        <SelectValue placeholder="选择质量" />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    <SelectItem value="fast">快速（压缩）</SelectItem>
                                                    <SelectItem value="medium">中等（推荐）</SelectItem>
                                                    <SelectItem value="slow">高质量（清晰）</SelectItem>
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            {/* 是否需要原片位置 */}
                            <FormField
                                control={form.control}
                                name="link"
                                render={({ field }) => (
                                    <FormItem className="flex items-center space-x-2">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                                id="link"
                                            />
                                        </FormControl>

                                        <FormLabel
                                            htmlFor="link"
                                            className="text-sm font-medium leading-none"
                                        >
                                            是否插入内容跳转链接
                                        </FormLabel>
                                    </FormItem>
                                )}
                            />
                            {/* 是否需要下载 */}
                            <FormField
                                control={form.control}
                                name="screenshot"
                                render={({ field }) => (
                                    <FormItem className="flex items-center space-x-2">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                                id="screenshot"
                                            />
                                        </FormControl>

                                        <FormLabel
                                            htmlFor="screenshot"
                                            className="text-sm font-medium leading-none"
                                        >
                                            是否插入视频截图
                                        </FormLabel>
                                    </FormItem>
                                )}
                            />

                            {/* 提交按钮 */}
                            <Button
                                type="submit"
                                className="w-full bg-primary cursor-pointer"
                            >
                                {isGenerating ? "正在生成…" : "生成笔记"}
                            </Button>
                        </form>
                    </Form>
                </TabsContent>
                
                <TabsContent value="upload">
                    <Form {...form}>
                        <div className="space-y-6">
                            <div className="space-y-2">
                                <div className="flex items-center justify-between my-3">
                                    <h2 className="block">本地视频上传</h2>
                                    <TooltipProvider>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <Info className="h-4 w-4 text-neutral-400 hover:text-primary cursor-pointer" />
                                            </TooltipTrigger>
                                            <TooltipContent>
                                                <p className="text-xs">上传本地视频文件，自动生成笔记</p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                </div>
                                
                                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:bg-gray-50" onClick={triggerFileInput}>
                                    <input 
                                        type="file" 
                                        ref={fileInputRef}
                                        accept="video/*" 
                                        onChange={handleFileChange} 
                                        className="hidden" 
                                    />
                                    <Upload className="h-10 w-10 text-gray-400 mx-auto mb-3" />
                                    <p className="text-sm text-gray-600 mb-1">点击或拖拽上传视频文件</p>
                                    <p className="text-xs text-gray-500">支持的格式: MP4, AVI, MOV等</p>
                                </div>
                                
                                {selectedFile && (
                                    <div className="mt-3 p-2 bg-gray-50 rounded flex items-center justify-between">
                                        <div className="truncate text-sm">
                                            <span className="font-medium">已选择: </span>
                                            {selectedFile.name}
                                        </div>
                                        <Button type="button" variant="ghost" size="sm" onClick={() => setSelectedFile(null)}>
                                            移除
                                        </Button>
                                    </div>
                                )}
                            </div>
                            
                            {/* 只保留截图选项 */}
                            <FormField
                                control={form.control}
                                name="screenshot"
                                render={({ field }) => (
                                    <FormItem className="flex items-center space-x-2">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                                id="upload_screenshot"
                                            />
                                        </FormControl>
                                        <FormLabel
                                            htmlFor="upload_screenshot"
                                            className="text-sm font-medium leading-none"
                                        >
                                            是否插入视频截图
                                        </FormLabel>
                                    </FormItem>
                                )}
                            />
                            
                            <Button
                                type="button"
                                className="w-full bg-primary cursor-pointer"
                                disabled={!selectedFile || isUploading}
                                onClick={handleFileUpload}
                            >
                                {isUploading ? "正在上传..." : "上传并生成笔记"}
                            </Button>
                        </div>
                    </Form>
                </TabsContent>

                <TabsContent value="audio">
                    <Form {...form}>
                        <div className="space-y-6">
                            <div className="space-y-2">
                                <div className="flex items-center justify-between my-3">
                                    <h2 className="block">音频文件上传</h2>
                                    <TooltipProvider>
                                        <Tooltip>
                                            <TooltipTrigger asChild>
                                                <Info className="h-4 w-4 text-neutral-400 hover:text-primary cursor-pointer" />
                                            </TooltipTrigger>
                                            <TooltipContent>
                                                <p className="text-xs">上传音频文件，自动生成笔记</p>
                                            </TooltipContent>
                                        </Tooltip>
                                    </TooltipProvider>
                                </div>
                                
                                <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:bg-gray-50" onClick={triggerAudioInput}>
                                    <input 
                                        type="file" 
                                        ref={audioInputRef}
                                        accept="audio/*" 
                                        onChange={handleAudioChange} 
                                        className="hidden" 
                                    />
                                    <FileAudio className="h-10 w-10 text-gray-400 mx-auto mb-3" />
                                    <p className="text-sm text-gray-600 mb-1">点击或拖拽上传音频文件</p>
                                    <p className="text-xs text-gray-500">支持的格式: MP3, WAV, M4A, AAC等</p>
                                </div>
                                
                                {selectedAudio && (
                                    <div className="mt-3 p-2 bg-gray-50 rounded flex items-center justify-between">
                                        <div className="truncate text-sm">
                                            <span className="font-medium">已选择: </span>
                                            {selectedAudio.name}
                                        </div>
                                        <Button type="button" variant="ghost" size="sm" onClick={() => setSelectedAudio(null)}>
                                            移除
                                        </Button>
                                    </div>
                                )}
                            </div>
                            
                            <Button
                                type="button"
                                className="w-full bg-primary cursor-pointer"
                                disabled={!selectedAudio || isUploading}
                                onClick={handleAudioUpload}
                            >
                                {isUploading ? "正在上传..." : "上传并生成笔记"}
                            </Button>
                        </div>
                    </Form>
                </TabsContent>
            </Tabs>
            
            <Separator className="my-6" />

            {/*生成历史    */}
            <div className="flex items-center gap-2 my-4">
                <Clock className="h-4 w-4 text-neutral-500" />
                <h2 className="text-base font-medium text-neutral-900">生成历史</h2>
            </div>
            <div className="flex-1 min-h-0 overflow-auto">
                <NoteHistory onSelect={setCurrentTask} selectedId={currentTaskId} />
            </div>

            {/* 添加一些额外的说明或功能介绍 */}
            <div className="mt-6 p-4 bg-primary-light rounded-lg">
                <h3 className="font-medium text-primary mb-2">功能介绍</h3>
                <ul className="text-sm space-y-2 text-neutral-600">
                    <li className="flex items-start gap-2">
                        <span className="text-primary font-bold">•</span>
                        <span>AI智能提取音视频内容，自动生成结构化笔记</span>
                    </li>
                    <li className="flex items-start gap-2">
                        <span className="text-primary font-bold">•</span>
                        <span>支持多种来源：哔哩哔哩、YouTube、本地视频、音频文件</span>
                    </li>
                    <li className="flex items-start gap-2">
                        <span className="text-primary font-bold">•</span>
                        <span>音频转录采用先进的Whisper模型，支持高质量语音识别</span>
                    </li>
                    <li className="flex items-start gap-2">
                        <span className="text-primary font-bold">•</span>
                        <span>可选自动截取视频帧作为笔记配图，增强可视化效果</span>
                    </li>
                    <li className="flex items-start gap-2">
                        <span className="text-primary font-bold">•</span>
                        <span>笔记支持Markdown格式，可一键复制或导出</span>
                    </li>
                    <li className="flex items-start gap-2">
                        <span className="text-primary font-bold">•</span>
                        <span>异步处理模式，支持后台生成与历史记录管理</span>
                    </li>
                </ul>
            </div>
        </div>
    )
}

export default NoteForm
